package com.yjj.teaching_platform.user.controller;

import com.yjj.teaching_platform.common.base.ErrorEnum;
import com.yjj.teaching_platform.common.base.ReturnObject;
import com.yjj.teaching_platform.user.entity.SysUser;
import com.yjj.teaching_platform.user.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


/**
 * @author yangjunjie
 */
@RestController
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @PostMapping("/login")
    public ReturnObject login(@RequestBody SysUser sysUser) {

        sysUser = sysUserService.getUserByName(sysUser.getUsername());
        if(sysUser == null) {
            return ReturnObject.fail(ErrorEnum.USERNAME_PASSWORD_ERROR);
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(sysUser.getUsername(),sysUser.getPassword());
        try{
            subject.login(usernamePasswordToken);
        }catch (AuthenticationException e) {
            e.printStackTrace();
            return ReturnObject.fail(ErrorEnum.USERNAME_PASSWORD_ERROR);
        }catch (AuthorizationException e) {
            e.printStackTrace();
            return ReturnObject.fail(ErrorEnum.PERMISSION_ERROR);
        }
        return ReturnObject.success(sysUser);
    }

    @GetMapping("/registry")
    public ReturnObject registry(String username, String password, String repeatPass, String verifyCode, HttpServletRequest request){

        return sysUserService.registry(username,password,repeatPass,verifyCode,request);
    }

}
